﻿package com.toncen.samepms.basic.action;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.struts2.ServletActionContext;

import com.toncen.samepms.basic.dao.DocumentRelationDao;
import com.toncen.samepms.basic.dao.DocumentsUploadDao;
import com.toncen.samepms.basic.domain.DocumentRelation;
import com.toncen.samepms.basic.domain.DocumentsUpload;
import com.toncen.samepms.basic.domain.User;
import com.toncen.samepms.common.AbstractDatabaseAction;
import com.sky.common.file.FileUtils;
import com.sky.common.http.HTTPUtils;
import com.sky.common.properties.PropertiesUtils;

/**
 * 描述：附件管理表BASIC_DOCUMENTS_UPLOAD的action文件
 * 
 * @author tch
 * 
 */
public class DocumentsUploadAction extends AbstractDatabaseAction<DocumentsUpload, DocumentsUploadDao> {
	/**
	 * 序列号
	 */
	private static final long serialVersionUID = 1337079669060L;

	String dir = "";

	String fileStyle = "";// 文件类型

	String filePath = "";// 文件保存服务器路径

	String encode = "";// 编码

	String fileExtensionStr = "";// 可以上传的附件类型
	
	String businessType = "";//可以上传的附件业务类型
	
	String businessTypeInitValue = "";//默认下拉框显示选项
	public String isUploadOperation = "true";//是否有上传的权限

	public DocumentsUploadAction() throws Exception {
		super();
	}

	static {
		// 读取配置文件中的文件存放路径
		Properties pp = null;
		try {
			pp = PropertiesUtils.getProperties("fileupload.properties");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		String documentUploadFilePath = pp.getProperty("uploadFilePath", "D:\\ComitWebFrame\\");
		// 创建文件夹，无则创建，有则不管
		File path = new File(documentUploadFilePath);
		if (false == path.exists()) {
			path.mkdirs();
		}
	}

	public String tempFileDir = "D:\\ComitWebFrame\\"; // 临时文件目录

	/**
	 * create:xl create date:2011-7-19上午10:03:45
	 * 包名：com.comit.zzyjgl.documentsupload.service 类名：UploadFileService.java
	 * 方法描述： 保存上传的文件至数据库中
	 * 
	 * @param items
	 *            上传文件集合
	 * @param request
	 * @throws NumberFormatException
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("deprecation")
	public void saveFile(List items, HttpServletRequest request, String fileType, String fileGrade,String businessType) throws NumberFormatException, Exception {
		String fileId = HTTPUtils.getRequestParameter(request, "sessionId").toString().trim();
		// 读取配置文件中的文件存放路径
		getResourceFilePath();

		// 创建文件夹，无则创建，有则不管
		File path = new File(tempFileDir);
		if (false == path.exists()) {
			path.mkdirs();
		}
		System.out.println(tempFileDir);

		Iterator iter = items.iterator();

		User user = getCurrentUser();// 获取当前用户信息
		String actionName = HTTPUtils.getRequestParameter(request, "actionName");// 所属模块
		String modelName = actionName.substring(actionName.lastIndexOf(".") + 1, actionName.length()).replace("Action", "");
		tempFileDir = tempFileDir + "\\" + modelName;
		path = new File(tempFileDir);
		if (false == path.exists()) {
			path.mkdirs();
		}
		long parentId = Long.parseLong(request.getParameter("parentId"));// 所属模块中的某条记录的主键
		DocumentRelation documentRelation = new DocumentRelation();
		documentRelation.setRecodeId(parentId);
		documentRelation.setCapability(actionName);
		//documentRelation.setBusinessTypeId(Integer.parseInt(businessType));//文件业务类型
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			DocumentsUpload upload = new DocumentsUpload();
			String displayFilename = "";
			if (item.isFormField()) {
				// processFormField
			} else {
				displayFilename = item.getName();// 文件路径
				String contentType = item.getContentType();// 文件内容类型
				String fileSize = String.valueOf(item.getSize());
				int i2 = displayFilename.lastIndexOf("\\");
				// 取得文件后缀 如(.txt)
				int dotIndex = displayFilename.lastIndexOf(".");// "."出现的索引
				int length = displayFilename.length();// 文件名的长度
				String fileSuffix = "";// 后缀名
				if (dotIndex > 0) {
					// 出现"."
					fileSuffix = displayFilename.substring(dotIndex, length);// 文件后缀
				}
				if (i2 > -1)
					displayFilename = displayFilename.substring(i2 + 1);// 取文件名

				upload.setDisplayFilename(displayFilename);// 显示文件名
				/*if(Integer.parseInt(fileSize)>(5*1024))
				{
					throw new Exception("请上传小于5KB的文件！");
				}*/
				upload.setFileSize(fileSize);// 文件大小
				upload.setFileSuffix(fileSuffix);// 文件后缀
				upload.setUploadDate(new Date());// 上传时间
				upload.setFileStyle(contentType);// 文件形式
				upload.setFileType(fileType);// 文件所属类型
				upload.setFileGrade(fileGrade);// 文件级别

				upload.setUploadUser(user.getId());// 上传用户
				String fileDes = "";
				upload.setFileDes(businessType);//文件业务类型// 文件描述
				upload.setState(1);// 文件状态，1是使用状态
				String remark = "";
				upload.setRemark(remark);// 备注
				DocumentsUploadDao dao = new DocumentsUploadDao();
				dao.save(upload);// 保存附件信息至数据库

				// 取记录主键为新的文件名
				upload.setFileName(upload.getId() + fileSuffix);// 存放文件名
				dao.save(upload);// 保存附件信息至数据库

				writeFile(request, fileId, parentId, item, upload, displayFilename);

				// 保存附件与功能模块中记录的关系
				documentRelation.setDocId(upload.getId());
				DocumentRelationDao documentRelationDao = new DocumentRelationDao();
				documentRelationDao.save(documentRelation);
			}
		}

	}

	/**
	 * @param request
	 * @param fileId
	 * @param item
	 * @param upload
	 * @param displayFilename
	 * @throws Exception
	 *             将文件写到指定路径下
	 */
	private void writeFile(HttpServletRequest request, String fileId, long parentId, FileItem item, DocumentsUpload upload, String displayFilename)
			throws Exception {
		File path;
		// 将文件写到指定路径下
		tempFileDir = tempFileDir + "\\" + parentId;
		path = new File(tempFileDir);
		if (false == path.exists()) {
			path.mkdirs();
		}
		File dirs = path;
		File uploadedFile = new File(dirs, displayFilename);
		item.write(uploadedFile);
		request.getSession().setAttribute("FileUpload.Progress." + fileId, "-1");

		String oldFilePath = tempFileDir + "\\" + displayFilename;// 文件路径+上传文件名
		String newFilePath = tempFileDir + "\\" + upload.getFileName();// 文件路径+重新生成的上传文件名
		oldFilePath = FileUtils.getStandardFilePath(oldFilePath);
		newFilePath = FileUtils.getStandardFilePath(newFilePath);
		// 文件重命名
		File f_old = new File(oldFilePath);
		File f_new = new File(newFilePath);
		f_old.renameTo(f_new);
	}

	/**
	 * @param saveFilePath
	 * @throws Exception
	 * @throws Exception
	 *             读取资源文件中配置的文件存放路径，拼装要保存的文件路径
	 */
	public String getResourceFilePath() throws Exception {
		Properties pp = PropertiesUtils.getProperties("fileupload.properties");// 文件存放默认路径配置
		tempFileDir = pp.getProperty("uploadFilePath", "D:\\ComitWebFrame\\");
		return tempFileDir;
	}

	/**
	 * 下载附件
	 * 
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public String downLoadAffix() throws Exception {
		DocumentsUpload file = new DocumentsUpload();
		DocumentsUploadDao dao = new DocumentsUploadDao();
		HttpServletRequest request = ServletActionContext.getRequest();
		long id = Long.parseLong(request.getParameter("domain.id").toString());
		try {
			file = (DocumentsUpload) load(id);// 取得文件信息
			setDomain(file);
			fileStyle = file.getFileStyle();
			filePath = dao.getAllFilePath(file);// 获取文件全路径
			encode = "UTF-8";
			dir = filePath;
			return SUCCESS;

		} catch (Exception e) {
			// LoggerUtils.debug(this, e);
			return INPUT;
		}

	}

	/**
	 * create:xl create date:2012-8-8下午02:19:10 方法描述： 获取附件类型
	 */
	public String onDoNew() throws Exception {
		logger.debug("执行【onDoNew】...");
		HttpServletRequest request = ServletActionContext.getRequest();
		fileExtensionStr = HTTPUtils.getRequestParameter(request, "fileExtensionStr");
		businessType = HTTPUtils.getRequestParameter(request, "businessType");
		businessTypeInitValue = HTTPUtils.getRequestParameter(request, "businessTypeInitValue");
		request.setAttribute("businessTypeInitValue", businessTypeInitValue);
		request.setAttribute("businessType", businessType);
		return SUCCESS;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getFileStyle() {
		return fileStyle;
	}

	public void setFileStyle(String fileStyle) {
		this.fileStyle = fileStyle;
	}

	public String getFileExtensionStr() {
		return fileExtensionStr;
	}

	public String getBusinessType() {
		return businessType;
	}

	public void setBusinessType(String businessType) {
		this.businessType = businessType;
	}

	public void setFileExtensionStr(String fileExtensionStr) {
		this.fileExtensionStr = fileExtensionStr;
	}

	public String getBusinessTypeInitValue() {
		return businessTypeInitValue;
	}

	public void setBusinessTypeInitValue(String businessTypeInitValue) {
		this.businessTypeInitValue = businessTypeInitValue;
	}

	public String getIsUploadOperation() {
		return isUploadOperation;
	}

	public void setIsUploadOperation(String isUploadOperation) {
		this.isUploadOperation = isUploadOperation;
	}

}
